#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <functional>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include "Thread.hpp"

#include "Log.hpp"

const char* chatpath = "/dev/pts/2";

enum
{
    ARGU_ERROR = 1,
    SOCK_ERROR,
    BIND_ERROR,
    RECV_ERROR
};

void SendMessage(int sockfd, sockaddr_in server, socklen_t serlen)
{
    while (true)
    {
        std::string s_buffer;
        std::cout << "Please Enter# ";
        std::getline(std::cin, s_buffer);
        ssize_t n = sendto(sockfd, s_buffer.c_str(), sizeof(s_buffer), 0, (sockaddr *)&server, serlen);

    }
}

void RecvMessage(int sockfd)
{
    char buffer[1024];
    while (true)
    {
        sockaddr_in peer;
        memset(&peer, 0, sizeof(peer));
        socklen_t plen = sizeof(peer);
        ssize_t n = recvfrom(sockfd, buffer, sizeof(buffer) - 2, 0, (sockaddr *)&peer, &plen);
        if (n < 0)
        {
            LOG(ERROR, "recv fail, exit code : %d", RECV_ERROR);
        }
        else if (n > 0)
        {
            buffer[n] = '\0';
            int fd = open(chatpath, O_WRONLY | O_APPEND);

            write(fd, buffer, strlen(buffer));
        }
    }
}

// ./client ip port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "Usage:\n\t" << argv[0] << " [ip] [port]\n";
        return ARGU_ERROR;
    }

    uint16_t port = std::stoi(argv[2]);
    std::string ip = argv[1];
    LOG(DEBUG, "ip : %s , port : %d\n", ip.c_str(), port);

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        LOG(FATAL, "create socket fail, exit code : %d\n", SOCK_ERROR);
    }
    LOG(INFO, "create socket success\n");

    sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = inet_addr(argv[1]);
    socklen_t serlen = sizeof(server);

    auto s = std::bind(SendMessage, sockfd, server, serlen);
    auto r = std::bind(RecvMessage, sockfd);
    Thread sd("sd", s);
    Thread rv("rv", r);

    sd.Start();
    rv.Start();

    sd.Join();
    rv.Join();

    return 0;
}